import { get, post, del, put } from '../utils/request';
import { ApiResponse, Torrent, TorrentDetail, PageResult } from '../types';
import axios from 'axios';
import Cookies from 'js-cookie';

/**
 * 获取种子列表
 */
export function getTorrents(params?: {
  page?: number;
  size?: number;
  category?: string;
  keyword?: string;
  promotionOnly?: boolean;
}) {
  return get<ApiResponse<PageResult<Torrent>>>('/torrents', params);
}

/**
 * 获取我的种子列表
 */
export function getMyTorrents(params?: {
  page?: number;
  size?: number;
}) {
  return get<ApiResponse<PageResult<Torrent>>>('/torrents/my', params);
}

/**
 * 获取种子详情
 */
export function getTorrentDetail(id: number) {
  return get<ApiResponse<TorrentDetail>>(`/torrents/${id}`);
}

/**
 * 上传种子
 */
export function uploadTorrent(formData: FormData) {
  return post<ApiResponse<Torrent>>('/torrents', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

/**
 * 下载种子文件
 */
export function downloadTorrent(id: number) {
  // 直接使用axios实例，绕过响应拦截器的JSON解析
  return axios.get(`/api/torrents/download/${id}`, { 
    responseType: 'blob',
    headers: {
      'Authorization': `Bearer ${Cookies.get('token')}`,
    },
  }).then((response: any) => response.data);
}

/**
 * 删除种子
 */
export function deleteTorrent(id: number) {
  return del<void>(`/torrents/${id}`);
}

/**
 * 设置种子促销
 */
export function setTorrentPromotion(id: number, data: {
  promotionType: number;
  durationHours: number;
}) {
  return put<ApiResponse<null>>(`/torrents/${id}/promotion`, data);
}

/**
 * 收藏种子
 */
export function favoriteTorrent(id: number) {
  return post<ApiResponse<null>>(`/torrents/${id}/favorite`);
}

/**
 * 取消收藏种子
 */
export function unfavoriteTorrent(id: number) {
  return del<ApiResponse<null>>(`/torrents/${id}/favorite`);
} 